const cloud = require('wx-server-sdk')
const fs = require('fs')
const path = require('path')
const http = require('http')
const hasha = require('hasha')
const os = require('os')
const filetype = require('file-type')

cloud.init({
  env: 'hm54-9ggy9ynhd3c080fb',
})

const db = cloud.database()

exports.main = async (event, context) => {
  let now = Date.now()
  const { _id: comic_id } = await db.collection('comic').add({
    data: {
      // comic_id: string
      name: data.name,
      author: data.author,
      desc: data.desc,
      tags: [],
      cover: data.cover,
      utime: now,
      ctime: now,
      url: data.url,
    },
  })

  const comic_section_col = db.collection('comic_section')
  const comic_page_col = db.collection('comic_page')

  const _ps = data.sections.map(async (v, index) => {
    const now = Date.now()
    const { _id: section_id } = await comic_section_col.add({
      data: {
        // section_id: string
        comic_id,
        name: v.name,
        index,
        utime: now,
        ctime: now,
        url: v.url,
      },
    })
    const _ps = v.pages.map(async (v, index) => {
      const now = Date.now()

      const stream = await getHttpImageStream(v.url)
      const path = await uploadFile(stream)
      await comic_page_col.add({
        data: {
          // page_id: string
          section_id,
          path,
          index,
          utime: now,
          ctime: now,
          url: v.url,
        },
      })
    })
    await Promise.all(_ps)
  })
  await Promise.all(_ps)

  return comic_id
}

async function getHttpImageStream(link) {
  return new Promise((resolve) => http.get(link, resolve))
}

async function uploadFile(stream) {
  let fp
  try {
    await _saveTempFile(stream)
    const [{ ext }, hash] = await Promise.all([
      filetype.fromFile(fp),
      hasha.fromFile(fp, { algorithm: 'md5' }),
    ])
    const cloudPath = 'comic/' + hash + '.' + ext
    const res = await cloud.uploadFile({
      cloudPath,
      fileContent: fs.createReadStream(fp),
    })
    if (res.fileID) return res.fileID
    throw new Error(res)
  } finally {
    await _delFile()
  }

  async function _saveTempFile(stream) {
    const _fp = path.join(os.tmpdir(), '_tmp' + Math.random())
    const file = fs.createWriteStream(_fp)
    fp = _fp
    stream.pipe(file)
    await new Promise((resolve) => stream.on('end', resolve))
    return _fp
  }
  async function _delFile() {
    if (fp) await new Promise((r, j) => fs.unlink(fp, (e) => (e ? j(e) : r())))
  }
}

const data = {
  name: '暴走武林学园',
  author: '狼烟动画',
  desc:
    '以20文钱就被娘卖到武当成为终身学徒的云无为，要怎样负担起史上最穷困潦倒的武当学院的日常？他们与峨眉，崆峒，华山，少林这几个学院之间又会发生怎样的爆笑纠葛？最终谁能入选武林的最高学府？',
  tags: [],
  cover: 'http://i-cdn.ibuka.cn/manga/cover/212787/201911201931/32x.jpg',
  url: 'http://www.buka.cn/detail/212787',
  sections: [
    {
      name: '暴走武林学园:1话 ',
      url: 'http://www.buka.cn/view/212787/65537.html',
      pages: [
        {
          url: 'http://i-cdn.ibuka.cn/pics/212787/65546/t3864017_0001.jpg',
        },
        {
          url: 'http://i-cdn.ibuka.cn/pics/212787/65546/t3864017_0002.jpg',
        },
        {
          url: 'http://i-cdn.ibuka.cn/pics/212787/65546/t3864017_0003.jpg',
        },
      ],
    },
  ],
}
